<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Promotions extends MY_Controller {
  
    private $emails = array();
    private $_emailConfig;
    
    public function __construct()
    {
        parent::__construct(); 
        
        $this->load->model('promotions_mod');
        $this->load->model('users_mod');
        $this->load->library('email');
  
        // define terms for emails
		$this->_emailConfig['mailtype'] = 'html';
        $this->_emailConfig['useragent'] = 'PHP CodeIgniter';      
    }
    
	/**
     *   
     *    
     */
    public function index( )
    {        
        $data['menu_page'] = "promotions"; // Koja je stranica. current menu item
        
        $data['states'] = $this->promotions_mod->getStates();
        $data['users'] = NULL;
        $data['users_from'] = $this->users_mod->getPromotionsUsersFromList();
        
        // Definisi koji se view ucitava
        $data['contents'] = 'promotions/promotions_home';
        
        $this->load->view('main',$data);
    }
    
    
    public function filter_submit() {
        try {
            $filter = $this->input->post('filter');
            $data['users'] = $this->promotions_mod->getUsers($filter);
            $num_users = count($data['users']);
            $html = $this->load->view('promotions/users_list', $data, true);
            $response = array(
                'ind' => 1,
                'msg' => "",
                'num_users' => $num_users,
                'html' => $html
            );
        } catch (Exception $e) {

            $response = array(
                'ind' => 0,
                'msg' => 'Following errors occured: <br />' . $e->getMessage(),
                'num_users' => 0,
                'html' => ''
            );
        }
        echo json_encode($response);
    }
    
    public function selected_submit() {
        try {
            $selected = $this->input->post('promotions_selected');
            //print_r($selected);
            if( $selected == NULL )
            {
               $response = array(
                    'ind' => 0,
                    'msg' => lang("must_choose_one_user")
                );
               
            }
            else 
            {
              $response = array(
                  'ind' => 1,
                  'msg' => "",
              );
            }
        } catch (Exception $e) {

            $response = array(
                'ind' => 0,
                'msg' => 'Following errors occured: <br />' . $e->getMessage(),
            );
        }

        echo json_encode($response);
    }
    
    public function send_promo_code()
    {
      try {
            
            $emails = $this->input->post('promotions_selected');
            $mailto = $this->input->post('mailto');
            $subject = $mailto['subject'];
            $from_id = $mailto['from_id'];
            if( isset($mailto['promotion_code']) )
              $promotion_code = $mailto['promotion_code'];
            else
              $promotion_code = NULL;
            if( isset($mailto['auto_code']) )
              $auto_code = true;
            else
              $auto_code = false;
            //$message = $this->input->post('message');
            $message = $_POST['message'];
            if( "" != $from_id && NULL != ($email = $this->users_mod->getUserEmail($from_id))  )
              $from = $email;
            else
              $from = $this->config->item('admin_mail_from');
            
            if( "" == $subject || "" == $message )
            {
              $response = array(
                    'ind' => 0,
                    'msg' => lang("must_enter_subject_and_message")
                );
            }else if ($this->_send_promotion_code($emails, $from, $subject, $message, $promotion_code, $auto_code )) {
                $response = array(
                    'ind' => 1,
                    'msg' => lang("mail_sent")
                );
            } else {
                $response = array(
                    'ind' => 0,
                    'msg' => lang("mail_not_sent")
                );
            }
        } catch (Exception $e) {

            $response = array(
                'ind' => 0,
                'msg' => 'Following errors occured: <br />' . $e->getMessage()
            );
        }
        echo json_encode($response);
    }
      
    
    private function _send_promotion_code($emails, $from, $subject, $message, $promotion_code, $auto_code )
    {     
       $this->load->helper('string');
       if( $auto_code ) // Promo kodovi se automatski generisu
       {                
         foreach ( $emails as $id=>$to )
         {
            $promo_code = random_string('alnum',5);
            $promo_coins = $this->config->item('promotion_code');
            $message = sprintf($message,$promo_code,$promo_coins);
            
            $this->_send_mail($to, $bcc, $from, $subject, $message);
            $this->promotions_mod->insertPromotionCode($id,$promo_code);
         }
         
         return true;
       }
       else if( $promotion_code != "" )
         return true;
       else
         return false;
    }
    
    private function _send_mail($to,$bcc,$from,$subject,$message)
    {
      $this->email->clear();
      $this->email->initialize($this->_emailConfig);
      
      $this->email->to($to);
      //$this->email->bcc($this->config->item('admin_mail_from'));    
      $this->email->from($from);
      $this->email->subject($subject);
      $this->email->message($message);

      if (!$this->email->send()) {        
        // Generate error (by CI)
        throw new Exception("Email cannot be sent. Try again or contact admin!");
        //echo $this->email->print_debugger();
        return false;
      }
      
      return true;
    }
    
    /*
          $emails_to = implode(",", $emails);
                    
          $this->email->clear();
          $this->email->initialize($this->_emailConfig);

          //$this->email->to($from);
          $this->email->to($this->config->item('admin_mail_from'));
          $this->email->bcc($emails_to);
          
          $this->email->from($from);
          $this->email->subject($subject);
          $this->email->message($message);
          
          if (!$this->email->send()) {
              // Generate error (by CI)
              throw new Exception("Email cannot be sent. Try again or contact admin!");
              //echo $this->email->print_debugger();
              return false;
          }          
       
        return true;
     
     */
   
}
/* End of file promotions.php */
/* Location: ./administration/controllers/promotions.php */